<template>
  <div class="shop_info">
    <!-- 店铺图片-->
    <van-form @submit="onSubmit" error-message-align="right" input-align="right">
      <van-field v-model="region_name" name="region_name" readonly label="店铺地址：" is-link placeholder="请选择店铺地址"
        @click="showPopup = true" />
        <!--  :rules="[{ required: true, message: '请输入店铺详细地址' }]"  -->
      <van-field v-model="address" name="address" label="店铺详细地址" placeholder="请输入店铺详细地址"
       />
      <van-field readonly clickable name="cate_name" :value="cate_name" label="店铺类型" placeholder="请选择店铺类型"
        @click="showMcc = true" is-link />
      <!-- :rules="[{ required: true, message: '请输入社会信用代码' }]" :rules="[{ required: true, message: '请选择经营类目' }]"  -->
      <!--  :rules="[{ required: true, message: '不能为空' }]" -->
      <van-field name="cover_url" label="" label-width="4rem">
        <template #label>
          <div class="shop_upload_text">
            <div>上传店铺图片</div>
            <div>保证照片清晰可见</div>
            <div @click="getExample('merchant_store_head')">查看示例</div>
          </div>
        </template>
        <template #input>
          <van-uploader v-model="cover_url" :max-count="1" :after-read="afterReadCover"
            :before-delete="uploadDleteCover">
            <img src="../../../../images/mine/icon_tup.png" alt="" class="shop_upload_img" />
          </van-uploader>
        </template>
      </van-field>
      <!-- :rules="[{ required: true, message: '不能为空' }]" -->
      <van-field name="head_image_url" label="" label-width="4rem" >
        <template #label>
          <div class="shop_upload_text">
            <div>上传公司大楼照</div>
            <div>保证照片清晰可见</div>
            <div @click="getExample('merchant_store_head')">查看示例</div>
          </div>
        </template>
        <template #input>
          <van-uploader v-model="head_image_url" :max-count="1" :after-read="afterReadHead"
            :before-delete="uploadDleteHead">
            <img src="../../../../images/mine/icon_tup.png" alt="" class="shop_upload_img">
          </van-uploader>
        </template>
      </van-field>
      <!-- :rules="[{ required: true, message: '不能为空' }]" -->
      <van-field name="company_front_image_url" label="" label-width="4rem"
        >
        <template #label>
          <div class="shop_upload_text">
            <div>上传前台照</div>
            <div>保证照片清晰可见</div>
            <div @click="getExample('merchant_check_out')">查看示例</div>
          </div>
        </template>
        <template #input>
          <van-uploader v-model="company_front_image_url" :max-count="1" :after-read="afterReadCheckout"
            :before-delete="uploadDleteCheckout">
            <img src="../../../../images/mine/icon_tup.png" alt="" class="shop_upload_img">
          </van-uploader>
        </template>
      </van-field>
      <!-- :rules="[{ required: true, message: '不能为空' }]" -->
      <van-field name="inside_image_url" label="" label-width="4rem" >
        <template #label>
          <div class="shop_upload_text">
            <div>上传商户内景照</div>
            <div>保证照片清晰可见</div>
            <div @click="getExample('merchant_inside')">查看示例</div>
          </div>
        </template>
        <template #input>
          <van-uploader v-model="inside_image_url" :max-count="1" :after-read="afterReadInside"
            :before-delete="uploadDleteInside">
            <img src="../../../../images/mine/icon_tup.png" alt="" class="shop_upload_img">
          </van-uploader>
        </template>
      </van-field>
      <!-- position: fixed;bottom: 0; -->
      <div style="width: 100%">
        <!-- <van-button round block type="default" @click="backBtn" style="width: 95%;margin: 0.32rem auto;"
        >上一步</van-button> -->
        <van-button round block type="info" native-type="submit" style="width: 95%;margin: 0.32rem auto;border-radius: 0.16rem;" 
          color="#FF6200">下一步</van-button>
      </div>
    </van-form>
    <van-button round block type="info" @click="onDraft" style="width: 95%;margin: 0.32rem auto;border-radius: 0.16rem;"  v-if="info.id<=0"
    color="#FF6200">暂存草稿</van-button>
    <!-- 省市区 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
        @change="onChange" @finish="onFinish" />
    </van-popup>
    <!-- 经营类目 -->
    <van-popup v-model="showMcc" position="bottom">
      <!-- <van-area :area-list="mccList" @confirm="onConfirmMcc" @cancel="showMcc = false" /> -->
      <van-cascader :field-names="fieldNames" v-model="cascaderValueMcc" title="请选择店铺类型" :options="optionsMcc"
        @close="showMcc = false" @finish="onFinishMcc" />
    </van-popup>
    <van-popup v-model="showExaplePopup" :style="{ width: '80%' }">
      <div class="popup_example">
        <img :src="example.content" alt="">
        <div>{{ example.tip_msg }}</div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { REGION_LIST } from "@/api/home";
import { getOssParams, uploadImage, uploadDelete, getExampleList } from "@/api/upload";
import { ONLINE_CATE_LIST ,CACHE_COMMIT,CACHE_INFO} from "@/api/mine";
import { setImageUrl ,getImageUrl} from '@/api/upload'; // Adjust the path accordingly
// ONLINE_
export default {
  props: ['info'],
  data() {
    return {
      // 省市区
      selectAreaList: [], // 已选中地区
      showPopup: false,
      cascaderValue: "",
      options: [],
      tabIndex: 0,
      // 经营类目
      optionsMcc: [],
      selectMccList: [],
      cascaderValueMcc: "",
      showMcc: false,
      fieldNames: {
        text: "name",
        value: "id",
        children: "children",
      },

      region_name: "",
      address: "",
      cover_url: [],
      head_image_url: [],
      company_front_image_url: [],
      inside_image_url: [],
      cate_name: "",
      example: {},
      showExaplePopup: false

    };
  },
  mounted() {
    this.fetchRegions(1, 0);
    this.fetchRegionsMcc(1, 0);
    // setTimeout(()=>{

    // },1000)s
    this.getInfo()
  },
  methods: {
    async getExample(key) {
      this.example = await getExampleList(this.$http, key)
      this.showExaplePopup = true
    },
    async getInfo() {
      if(this.info.id<=0){
            let params = {
        type: 'shop',
        key: 'shopPic',

      }
        this.$http.get(CACHE_INFO, { params: params }).then(res => {
          if(res.data.content!=''){
          const data = JSON.parse(res.data.content);
          // 回显数据
        this.cate_name=data.cate_name,
        this.cate_id=data.cate_id,
        this.cascaderValueMcc=data.cate_id
        this.region_name=data.region_name
        //  this.fetchRegions(this.info.province_code, 1)
        //  this.fetchRegions(this.info.city_code, 2)
        //  this.region_name=data.region_name
        this.region_code=data.region_code
        this.cascaderValue=data.region_code
        this.address=data.address,
        this.cover_url=setImageUrl(data.cover_url),
        this.company_front_image_url= setImageUrl(data.image_data.company_front_image_url),
        this.inside_image_url=setImageUrl(data.image_data.inside_image_url),
        this.head_image_url= setImageUrl(data.image_data.head_image_url)
          }
      })
      }else{
      this.cate_name = this.info.cate_name;
      this.cate_id = this.info.cate_id;
      this.cascaderValueMcc = this.info.cate_id;
      if (this.info.city_code != 0) {
        await this.fetchRegions(this.info.province_code, 1);
        await this.fetchRegions(this.info.city_code, 2);
        // await this.fetchRegions(this.info.county_code, 3);
        this.region_name = this.info.region_name;
        this.region_code = this.info.region_code;
        this.cascaderValue = this.info.region_code;
        //  this.fetchRegions(this.info.county_code, 4);
      }
      // if()
      // console.log(this.options,"this");


      this.address = this.info.address;
      this.cover_url = this.info.cover_url == '' ? [] : [{ url: this.info.cover_url }]
      this.company_front_image_url = this.info.image_data.company_front_image_url == '' ? [] : [{ url: this.info.image_data.company_front_image_url }]
      this.inside_image_url = this.info.image_data.inside_image_url == '' ? [] : [{ url: this.info.image_data.inside_image_url }]
      this.head_image_url = this.info.image_data.head_image_url == '' ? [] : [{ url: this.info.image_data.head_image_url }]
    }
    },
    // 上传门头照
    async afterReadHead(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error('OSS参数未正确设置');
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.head_image_url);
      } catch (error) {
        console.error('处理上传错误:', error);
      }
    },
    // 删除门头照
    uploadDleteHead(file) {
      this.head_image_url = uploadDelete(file, this.head_image_url);

    },
    // 上传收银台
    async afterReadCheckout(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error('OSS参数未正确设置');
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.company_front_image_url);
      } catch (error) {
        console.error('处理上传错误:', error);
      }
    },
    // 删除收银台
    uploadDleteCheckout(file) {
      this.company_front_image_url = uploadDelete(file, this.company_front_image_url);
    },
    // 上传内景
    async afterReadInside(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error('OSS参数未正确设置');
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.inside_image_url);
      } catch (error) {
        console.error('处理上传错误:', error);
      }
    },
    // 删除内景
    uploadDleteInside(file) {
      this.inside_image_url = uploadDelete(file, this.inside_image_url);
    },
    // 选择器变化时的回调
    onChange(res) {
      this.tabIndex = res.tabIndex;
      if (this.tabIndex === 2) {
        return;
      }
      //   console.log(res, "jj");
      //点击加载下一级回调
      this.getSpaceListAgain(res.selectedOptions, res.value);
    },
    getSpaceListAgain(selectedOptions, value) {
      this.$http
        .get(REGION_LIST, {
          params: {
            code: value,
          },
        })
        .then((res) => {
          const { data } = res;

          if (data && data.length) {
            this.setOptions(selectedOptions, data);
          }
        });
    },
    setOptions(selectedOptions, data) {
      let _options = this.options;
      selectedOptions.forEach((item, index) => {
        if (index) {
          //不是第一个则取下一级children
          _options = _options.children;
        }
        _options =
          _options[_options.findIndex((_item) => _item.value === item.value)];
      });
      //找到最后一级
      _options.children = data.map((item) => {
        return {
          text: item.name,
          value: item.code,
          children: this.tabIndex == 1 ? null : [],
        };
      });
    },
    // 确定省市区
    onFinish({ selectedOptions }) {
      this.showPopup = false;

      this.selectAreaList = selectedOptions;

      selectedOptions = selectedOptions.filter((item) => {
        return item.value !== 0;
      });

      //   console.log(selectedOptions, "ll");

      this.region_name = selectedOptions.map((option) => option.text).join("/");
    },
    async fetchRegions(parentCode, level) {
      const res = await this.$http.get(REGION_LIST, {
        params: {
          code: parentCode,
        },
      });
      const { data } = res;

      // 省级
      if (level === 0) {
        data.forEach((item) => {
          this.options.push({
            text: item.name,
            value: item.code,
            children: [],
          });
        });
      } else if (level === 1) {
        // 市级数据
        const province = this.options.find((item) => item.value === parentCode);
        if (province) {
          province.children = data.map((item) => ({
            text: item.name,
            value: item.code,
            children: [],
          }));
        }
      } else if (level === 2) {
        // 区/县级数据
        this.options.forEach((province) => {
          const city = province.children.find(
            (item) => item.value === parentCode
          );
          if (city) {
            city.children = data.map((item) => ({
              text: item.name,
              value: item.code,
              //   children: [],
            }));
          }
        });
      }
      // else if (level === 3) {
      //   // 街道数据
      //   this.options.forEach((province) => {
      //     province.children.forEach((city) => {
      //       const county = city.children.find(
      //         (item) => item.value === parentCode
      //       );
      //       if (county) {
      //         county.children = data.map((item) => ({
      //           text: item.name,
      //           value: item.code,
      //         }));
      //       }
      //     });
      //   });
      // }
    },
    // 经营类目
    async fetchRegionsMcc(parentCode, level) {
      //
      const res = await this.$http.get(ONLINE_CATE_LIST);
      this.optionsMcc = res.data;
    },
    // 确定类目
    onFinishMcc({ selectedOptions }) {
      this.showMcc = false;

      this.selectMccList = selectedOptions;

      selectedOptions = selectedOptions.filter((item) => {
        return item.value !== 0;
      });

      //   console.log(selectedOptions, "333");

      this.cate_name = selectedOptions.map((option) => option.name).join("/");
    },
    // 店铺图片
    async afterReadCover(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error("OSS参数未正确设置");
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.cover_url);
      } catch (error) {
        console.error("处理上传错误:", error);
      }
    },
    // 删除经营资质
    uploadDleteCover(file) {
      this.cover_url = uploadDelete(file, this.cover_url);
    },
    onSubmit(values) {
      // if (this.info.city_code == 0) {
      //   this.cate_id =
      //     this.selectMccList.length > 0
      //       ? this.selectMccList[this.selectMccList.length - 1].id
      //       : null;
      //   if (this.selectAreaList.length > 0) {
      //     const lastIndex = this.selectAreaList.length - 1;
      //     this.region_code =
      //       this.selectAreaList[lastIndex].value === 0 && lastIndex > 0
      //         ? this.selectAreaList[lastIndex - 1].value
      //         : this.selectAreaList[lastIndex].value;
      //   } else {
      //     this.region_code = null; // 如果没有选择区域，设置为 null 或其他默认值
      //     this.region_name = null; // 如果没有选择区域，设置为 null 或其他默认值
      //   }
      // }

      let params = {
        region_code:  this.cascaderValue,
        region_name: this.region_name,
        cate_id: this.cate_id || this.cascaderValueMcc,
        cate_name: this.cate_name
      }
      
      let datas = {
        // cate_name: this.cate_name,
        // cate_id: this.cate_id,
        cascaderValueMcc: this.cate_id || this.cascaderValueMcc,
        // region_name:this.region_name,
        // region_code:this.region_code,
        ...params,
        cascaderValue:this.cascaderValue,
        address: this.address,
        cover_url: getImageUrl(this.cover_url),
        image_data:{
          company_front_image_url: getImageUrl(this.company_front_image_url),
          inside_image_url: getImageUrl(this.inside_image_url),
          head_image_url: getImageUrl(this.head_image_url)
        }
      }
      let data = {
        type: 'shop',
        key: 'shopPic',
        content: JSON.stringify(datas)
      }
      if(this.info.id<=0){
      this.$http.post(CACHE_COMMIT, data).then(res => {
      })
    }
      this.$emit("shopPic", values, params);
    },
    onDraft() {
      let params = {
        cate_name: this.cate_name,
        cate_id: this.cate_id || this.cascaderValueMcc,
        cascaderValueMcc: this.cate_id,
        region_name:this.region_name,
        region_code: this.cascaderValue,
        cascaderValue: this.cascaderValue,
        address: this.address,
        cover_url: getImageUrl(this.cover_url),
        image_data:{
          company_front_image_url: getImageUrl(this.company_front_image_url),
        inside_image_url: getImageUrl(this.inside_image_url),
        head_image_url: getImageUrl(this.head_image_url)
        }
      }
      let data = {
        type: 'shop',
        key: 'shopPic',
        content: JSON.stringify(params)
      }
      this.$http.post(CACHE_COMMIT, data).then(res => {
        this.$toast('暂存成功')
      })
    },
    backBtn() {
      this.$emit("goBack", 0)
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .van-cell {
  background: transparent;
}

.shop_info {
  ::v-deep .van-icon {
    color: #c0c0c0 !important;
  }
}

.shop_upload_text {
  // line-height: 0.5rem;
  line-height: 0.6rem;
  text-align: left;
  font-style: normal;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;

  div:nth-child(1) {
    // font-weight: 400;
    font-size: 0.28rem;
    color: #333333;
  }

  div:nth-child(2) {
    font-size: 0.24rem;
    color: #999999;
  }

  div:nth-child(3) {
    font-size: 0.24rem;
    color: #FF6200;
  }
}

.shop_upload_img {
  width: 0.64rem;
  height: 0.64rem;
  margin-top: 70%;
}

.popup_example {
  padding-bottom: 0.2rem;

  img {
    width: 100%;
  }

  div {
    padding: 0 .12rem;
    box-sizing: border-box;
    font-size: 0.28rem;
  }

}
</style>
